package com.bzxgc.sgwer.service.impl.user;

import com.bzxgc.sgwer.dao.user.UserRoleMapper;
import com.bzxgc.sgwer.entity.user.UserRole;
import com.bzxgc.sgwer.service.user.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("userRoleService")
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    @Transactional
    public void addUserRoleBatch(Long[] userIds, Long[] roleIds, Long roleId) {
        deleteUserRoleByUserIds(userIds);
        List<UserRole> userRoleList = new ArrayList<>();
        Date currentTime = new Date();
        for (Long userId : userIds) {
            for (Long rId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(rId);
                userRole.setAddTime(currentTime);
                userRole.setMainRole("false");
                if (roleId == rId) {
                    userRole.setMainRole("true");
                }
                userRoleList.add(userRole);
            }
        }
        userRoleMapper.addUserRoleBatch(userRoleList);
    }

    @Override
    public void deleteUserRoleByUserIds(Long[] userIds) {
        userRoleMapper.deleteUserRoleByUserIds(userIds);
    }

    @Override
    public List<UserRole> getUserRoleByUserId(Long userId) {
        return userRoleMapper.getUserRoleByUserId(userId);
    }

}
